package com.squeekeek.util.qrcode;

import android.content.Context;
import android.hardware.Camera;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class PreviewQRPhoto extends SurfaceView implements SurfaceHolder.Callback {
	private SurfaceHolder hSHolder;
	private Camera hCamera;

	public PreviewQRPhoto(Context context, Camera camera) {
		super(context);
		
		hCamera = camera;
		
		hSHolder = getHolder();
		hSHolder.addCallback(this);
		hSHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		try {
			hCamera.setPreviewDisplay(holder);
		}
		catch(Exception e) {
			Log.d("QRCode", "Cannot set camera preview: " + e.getMessage());
		}
		
	}
	
	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
		if(hSHolder.getSurface() == null) {
			return;
		}
		
		try {
			hCamera.stopPreview();
		}
		catch(Exception e) {
			Log.d("QRCode", "Cannot stop preview: " + e.getMessage());
		}
		
		try {
			hCamera.setPreviewDisplay(hSHolder);
			hCamera.startPreview();
		}
		catch(Exception e) {
			Log.d("QRCode", "Cannot restart camera preview: " + e.getMessage());
		}
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		try {
			hCamera.stopPreview();
		}
		catch(Exception e) {
			Log.d("QRCode", "Failed to stop preview in destroy(): " + e.getMessage());
		}
		
		hSHolder = null;
	}

}
